﻿using AuthCenter.API.Application.Command.Role;
using AuthCenter.Domain;
using AuthCenter.Domain.Account;
using AuthCenter.ErrorCode;
using AuthCenter.Intertructrue.Interface;
using AutoMapper;
using MediatR;
using System.Transactions;
using Yitter.IdGenerator;

namespace AuthCenter.API.Application.Handler.Role
{
    public class CreateRoleHandler : IRequestHandler<CreateRoleCommand, APIResult<int>>
    {
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IBaseRepository<LogModel> logRepo;
        private readonly IMapper mapper;

        public CreateRoleHandler(IBaseRepository<RoleModel> roleRepo,
                                 IBaseRepository<LogModel> logRepo,
                                 IMapper mapper)
        {
            this.roleRepo = roleRepo;
            this.logRepo = logRepo;
            this.mapper = mapper;
        }
        public Task<APIResult<int>> Handle(CreateRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var res = roleRepo.GetAll().FirstOrDefault(x => x.RoleName == request.RoleName);
            if (res != null)
            {
                result.Message = "已拥有该角色！";
                result.Code = APIEnum.Fail;
                return Task.FromResult(result);
            }
            var model = mapper.Map<RoleModel>(request);
            model.Id = YitIdHelper.NextId();
            model.CreateName = request.LoginName;
            model.CreateDate = DateTime.Now;
            LogModel logModel = new LogModel()
            {
                Id = YitIdHelper.NextId(),
                LogContent = $"添加角色信息成功,操作人为{request.LoginName}",
                CreateName = request.LoginName,
                CreateDate = DateTime.Now
            };
            int r = 0;
            int r1 = 0;
            using(TransactionScope tran = new TransactionScope())
            {
                try
                {
                    r = roleRepo.AddAsync(model).Result;
                    r1 = logRepo.AddAsync(logModel).Result;
                    tran.Complete();
                }
                catch (Exception)
                {

                    throw;
                }
            }
            if (r > 0)
            {
                result.Message = "添加角色信息成功";
                result.Code = APIEnum.Ok;
                result.Data = r;
            }
            else
            {
                result.Message = "添加角色信息失败";
                result.Code = APIEnum.Fail;
                result.Data = r;
            }
            return Task.FromResult(result);
        }
    }
}
